<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace plugins\redis\index\controller;

use app\index\BaseController;

class Index extends BaseController
{
    protected function initialize()
    {
        parent::initialize();
        $this->redis = new \Redis();
        $this->redis->connect('127.0.0.1', 6379);
        // 抢购商品名称
        $this->goodsKey = 'goodsName';
        // 抢购成功用户
        $this->usersKey = 'usersName';
    }
    
    /**
     * 抢购设置
     */
    public function setStock()
    {
        $number = 100;
        // 商品信息从链表的尾部添加
        for ($i = 0; $i < $number; $i ++) {
            $this->redis->rPush($this->goodsKey, $i);
        }
        // 设置抢购时长为1小时
        $this->redis->expire($this->goodsKey, 60*60);
        return '模拟共：' . $this->redis->llen($this->goodsKey) . '件商品参与抢购活动';
    }
    
    /**
     * 用户抢购（ab压力测试）
     */
    public function buy()
    {
        if (empty($this->redis->llen($this->goodsKey))) {
            return '亲亲，商品没有库存了！';
        }
        // 从链表的头部删除一个元素(先进先出)
        $this->redis->lpop($this->goodsKey);
        // 模拟用户id
        $userId = md5(uniqid('user').time());
        // 幸运用户存在集合中
        $this->redis->hSet($this->usersKey, $userId, $this->goodsKey);
        return '亲亲，抢购成功啦';
    }
    
    /**
     * 查看幸运用户
     */
    public function getAll()
    {
        halt($this->redis->hGetAll($this->usersKey));
    }
}